package cn.edu.gzhu.workOrderManagement.aspect;


import cn.edu.gzhu.workOrderManagement.annotation.AutoFill;
import cn.edu.gzhu.workOrderManagement.constants.OperationConstant;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 自动填充createTime和updateTime的切面类
 * @author chen xi
 */


@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    @Pointcut("execution(* cn.edu.gzhu.workOrderManagement.mapper.*.*(..)) && @annotation(cn.edu.gzhu.workOrderManagement.annotation.AutoFill)")
    public void autoFill(){}
    @Before("autoFill()")
    public void doFill(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        log.info("开始自动填充时间");
        //获取方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //从方法签名获取注解
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);

        String value = autoFill.operationType();
        //获取传入的参数，必须是一个包含setUpdateTime或者setUpdateTime的对象
        Object arg = joinPoint.getArgs()[0];
        //根据传入的对象参数去执行方法
        Method setUpdateTime = arg.getClass().getMethod("setUpdateTime", LocalDateTime.class);
        Method setCreateTime = arg.getClass().getMethod("setCreateTime", LocalDateTime.class);


        if (OperationConstant.INSERT.equals(value)) {

            setCreateTime.invoke(arg, LocalDateTime.now());

            setUpdateTime.invoke(arg, LocalDateTime.now());
            log.info("自动填充成功");
        }
        else if (OperationConstant.UPDATE.equals(value)) {

            setUpdateTime.invoke(arg, LocalDateTime.now());
            log.info("自动填充成功");
        }

    }

}
